import util from "../../util";
export default class parentInstance {
  constructor(clz, api) {
    this.util = util;
    this.record = {};
    this.info = null;
    this.pointer = null;
    this.modelMap = null;
    this.clz = clz;
    this.api = api;
    this.valueRecord = {};
  }
  setRecord(record = this.clz.tpl()) {
    this.record = record;
  }
  /***
   * 新增
   * @param record
   * @returns {Promise<boolean|*>}
   */
  async add(record = this.record) {
    if (!record || !record.className || record.className == "") {
      return false;
    }
    let newRecord = Object.assign(this.clz.tpl(), record);
    let result = await this.api
      .add(newRecord)
      .then((data) => {
        if (!!data) {
          this.setRecord(data);
          this.setValueRecord();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /***
   * 新增
   * @param record
   * @returns {Promise<boolean|*>}
   */
  async addAndInitWeb(record = this.record) {
    if (!record || !record.className || record.className == "") {
      return false;
    }
    let newRecord = Object.assign(this.clz.tpl(), record);
    let result = await this.api
      .addAndInitWeb(newRecord)
      .then((data) => {
        if (!!data) {
          this.setRecord(data);
          this.setValueRecord();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 删除
   * @returns {Promise<boolean|*>}
   */
  async delete(filter) {
    let result = await this.api
      .delete({ condition: filter })
      .then((flag) => {
        if (flag) {
          this.setRecord({});
          this.setValueRecord();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteById(id) {
    let result = await this.api
      .deleteById(id)
      .then((flag) => {
        if (flag) {
          this.setRecord({});
          this.setValueRecord();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteByClassName(className) {
    let result = await this.api
      .deleteByClassName(className)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 更新
   * @returns {Promise<*>}
   */
  async updateById(params = {}) {
    let updateRec = this.record;
    let result = await this.api
      .updateById(updateRec, params)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async updateHier(data = this.record) {
    let result = await this.api
      .updateHier(data)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async saveHier(data = this.record) {
    let result = await this.api
      .saveHier(data)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async deleteHier(ids) {
    let result = await this.api
      .deleteHier(ids)
      .then((flag) => {
        if (flag) {
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 查询
   * @param param
   * @returns {Promise<*>}
   */
  async queryById(id) {
    let result = await this.api
      .query({ condition: `id=${id}` })
      .then((data) => {
        if (!!data) {
          this.setRecord(data[0]);
          this.setValueRecord();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  async query(
    condition,
    hierValueCondition = "",
    otherParams = {},
    like = false
  ) {
    hierValueCondition = hierValueCondition || "1=1";
    let filterStr = condition;
    if (condition.constructor === Object) {
      filterStr = this.setFilteStr(condition, like);
    }
    let hierFilterStr = hierValueCondition;
    if (hierValueCondition.constructor === Object) {
      hierFilterStr = this.setFilteStr(hierValueCondition, like);
    }
    let result = await this.api
      .query({
        condition: filterStr,
        hierValueCondition: hierFilterStr,
        ...otherParams,
      })
      .then((data) => {
        if (!!data) {
          this.setRecord(data.length > 0 ? data[0] : {});
          this.setValueRecord();
          return true;
        } else {
          return false;
        }
      })
      .catch((err) => {
        return false;
      });
    return result;
  }
  /**
   * 新增模板
   * @returns {}
   */
  static tpl() {
    return {
      // id: "",
      name: "",
      type: "",
      className: "",
      version: "1.0",
      published: true,
      values: {},
      // hier:[],
      web: {},
      others: {},
      comments: "",
    };
  }
  // 动态生成当前实例对应的字段表
  /**
   * 当前记录
   */
  calcModelFields(modelList, curRecord = this.record) {
    let curModel = modelList.filter(
      (item) => item.className === curRecord.className
    );
    let modelFieldList = [];

    if (curModel && curModel.length) {
      let values = curRecord.values || {};
      let fieldObj = {};

      curModel[0].properties.forEach((item) => {
        if (!fieldObj[item.name]) {
          curRecord.values[item.name] = values[item.name];
          fieldObj[item.name] = true; // 去重处理
          if (item.type === "DateTime" && values[item.name]) {
            curRecord.values[item.name] = new Date(values[item.name]);
          }
          modelFieldList.push(this.buildFormField(item));
        }
      });
    }
    return modelFieldList;
  }
  // 构建表单字段信息
  buildFormField(item) {
    let field = {
      key: item.name,
      title: item.name,
    };
    switch (item.type) {
      case "Double":
        field = {
          ...field,
          config: {
            type: "number",
            min: 0,
            max: 99999999,
            precision: 2,
          },
        };
        break;
      case "Integer":
        field = {
          ...field,
          config: {
            type: "number",
            min: 0,
            max: 99999999,
            precision: 0,
          },
        };
        break;
      case "Boolean":
        field = {
          ...field,
          config: {
            type: "check",
          },
        };
        break;
      case "DateTime":
        field = {
          ...field,
          config: {
            type: "datetime",
          },
        };
        break;
      default:
        field = {
          ...field,
          config: {
            type: "text",
          },
        };
        break;
    }
    return field;
  }
  setValueRecord() {
    this.valueRecord = !!this.record.values
      ? {
          ...this.record.values,
          ...this.record,
        }
      : {};
    return this.valueRecord;
  }
  setFilteStr(filter, like = true) {
    if (!!filter && filter.constructor === Object) {
      for (let key in filter) {
        (filter[key] === "" || filter[key] === null) && delete filter[key];
      }
    } //删除查询项中属性值为空的查询条件
    filter = this.bulidFilter(filter, like ? "like" : "=");
    return filter;
  }
  bulidFilter(filterMap, sign = "like") {
    let arr = [];
    if (!!filterMap) {
      Object.keys(filterMap).map((key) => {
        let curItem = filterMap[key];
        let type = typeof curItem;
        let strWrap = type === "number" || type === "boolean" ? "" : "'";

        if (curItem !== "" && curItem !== undefined && curItem !== null) {
          if (
            sign === "like" &&
            strWrap &&
            key != "className" &&
            key != "type" &&
            key != "id"
          ) {
            arr.push(`${key} like ${strWrap}%${curItem}%${strWrap}`);
          } else {
            arr.push(`${key} ${"=="} ${strWrap}${curItem}${strWrap}`);
          }
        }
      });
    }
    return arr.join(" && ");
  }
}
